package lesson.subject;

import lesson.base.BaseServlet;
import lesson.permission.Role;
import lesson.user.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.List;

@WebServlet("/subject/*")
@Role(User.ROLE_ADMIN)
public class SubjectServlet extends BaseServlet {

    private SubjectService subjectService = new SubjectService();

    /**
     * 学科管理的首页
     */
    public void index() {
        forwardJsp("/pages/subject/index");
    }

    /**
     * 学科管理的编辑页面
     */
    public void edit(Integer id) {
        if (id != null) {
            Subject subject = subjectService.getById(id);
            getRequest().setAttribute("subject", subject);
        }
        forwardJsp("/pages/subject/edit");
    }


    /**
     * 查询学科
     */
    public void list(String keywords) throws ServletException, IOException {
        List<Subject> list = subjectService.list(keywords);
        writeJSON(true, null, list);
    }


    /**
     * 删除学科
     * @param id
     */
    public void del(Integer id) throws ServletException, IOException {
        String result = subjectService.del(id);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }


    /**
     * 保存学科
     * @param id
     * @param name
     * @throws ServletException
     * @throws IOException
     */
    public void save(Integer id, String name) throws ServletException, IOException {

        String result = subjectService.saveSubject(id, name);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }


}
